/**
 * Created by yl on 2016/5/3 0003.
 */
Array.removeRange = function(array, from, to) {
  var rest = array.slice((to || from) + 1 || array.length);
  array.length = from < 0 ? array.length + from : from;
  return array.push.apply(array, rest);
};
function removeAt(array,idx)
{
  if(! Array.prototype.isPrototypeOf(array)){
    return null;//根据Null可以判断本次调用失败
  }
  var idx = parseInt(idx),
    iLen = idx.length;
  if(idx < 0 || idx >= iLen){
    return null;//根据Null可以判断本次调用失败
  }
  var aRet = [];//与NULL不同
  return aRet=array.slice(0,idx).concat(array.slice(idx+1));
}

var AppService ={
  urlroot: "http://euvee.vicp.co/rest/site/",
  init: function(){
    Vue.http.options.root = this.urlroot;},
  find: function(inputQuery, pagenum, pagesteps, items, success_callback, error_callback){
    var url = this.urlroot;
    Vue.http.get(url, function(data, status, request){
      var i = data.length;
      success_callback(data, status, request);
    })
      .error(function (data, status, request) {
        alert("svc.find: fetch data from backend server failed! " + data + ' ' + status + ' ' + request);
        if (error_callback != null)
        {
          error_callback(data, status, request);
        }
      });
  },
  get: function(id, callback){
    Vue.http.get(this.urlroot + this.id, callback);
  },
  getById: function(items, id){
    var result = null;
    var i = items.length;
    while (i--) {
      if (items[i].id == id)
      {
        result = items[i];
        break;
      }
    }
    return result;
  },
  indexof: function(items, id){
    var idx = null;
    var i = items.length;
    while (i--) {
      if (items[i].id == id)
      {
        idx = i;
        break;
      }
    }
    return i;
  },
  resetItem: function(item){
    item.id = null;
    item.owner = null;
    item.code = null;
    item.reluserid = 0;
    item.securitylevel = 0;
    item.idcard = null;
    item.firstname = "";
    item.midname = "";
    item.lastname = "";
    item.secname = "";
    item.nickname = "";
    item.respectname = "";
    item.gender = '-';
    item.email = "zhagnsan@163.com";
    item.mobilephone = "1373214421";
    item.im = "";
    item.qq = "";
    item.weixin = "";
    item.affiliation = "";
    item.employeeid = "";
    item.address = null;
    item.zip = null;
    item.birthday = null;
    item.sculpture = null;
    item.objectstate = null;
    item.rowstate = null;
    item.note = null;
    item.upduser = null;
    item.upddate = null;
    item.crtuser = null;
    item.crtdate = null;
    //
    item.selected = false;}
};
var filelist=new Vue({
  el:'#filelist',
  data:{
    items:[
    ],
    id:'',
    shortname:'',
    category:'',
    dataTimeStr:'',
    suffix:'',
    state:''
  },
  urlroot: "http://localhost:8080/rest/sedt",
  init: function(){
    this.$http.options.root = this.urlroot;
  },
  ready: function(inputQuery, pagenum, pagesteps, items, success_callback, error_callback) {
    this.$http.get("http://localhost:8080/rest/sedt", function(data) {
      this.$set('items', data);
      success_callback(data, status, request);
    }).error(function (data, status, request) {
        alert("svc.find: fetch data from backend server failed! " + data + ' ' + status + ' ' + request);
        if (error_callback != null)
        {
          error_callback(data, status, request);
        }
      });
  },
  methods:{
    onEdit: function(item, e){
      console.log('editItem: ' + item.id.toString());
      this.curitem = item;
      this.setMode('modeEdit');
    },
    onRemoveItem: function(item, e){
      console.log('removeItem' + item);
      svc.remove(item);
      this.items.$remove(item);
      this.setMode('modeList');
    },
    setMode: function(newmode){
      if (this.mode != newmode)
      {
        this.mode = newmode;
        switch (newmode)
        {
          case "modeList":
            this.modeTitle = "";
            break;
          case "modeItemView":
            this.modeTitle = " [详情]";
            break;
          case "modeEdit":
            this.modeTitle = " [编辑]";
            break;
          case "modeAddNew":
            this.modeTitle = " [新增]";
            resetItem(this.curitem);
            this.curitem.id=null;
            break;
          default:
            this.modeTitle = "";
        }
      }
    }}
});


var svc = Object.create(AppService);


Vue.component('itemeditor', {
  template: '#itemeditor-tpl',
  props:[{
    name: 'item',
    type: Object,
    twoWay: false,
    required: true
  },
    {
      name: 'mode',
      type: String
      //default: 'modeList',
    },
    {
      name: 'onSubmit',
      type: Function
      //required: true,
    },
    {
      name: 'onCancel',
      type: Function
    }
  ],

  data: function () {
    return {
      result: ''
    }
  },

  methods: {
    onSubmitClick: function(e){
      console.log("onSubmitClick: inside component itemeditor");
      this.result = this.onSubmit(this.mode, this.item);
    },
    onCancelClick: function(e){
      console.log("onCancelClick: inside component itemeditor");
      this.onCancel(this.mode, this.item);
    }
  }
});

// register modal component
Vue.component('modal', {
  template: '#modal-template',
  props: {
    show: {
      type: Boolean,
      required: true,
      twoWay: true
    }
  }
});

Vue.component('datatable', {
  template: '#datatable-tpl',
  props:[{
    name: 'tabledef',
    type: Object,
    twoWay: false,
    required: true
  },
    {
      name: 'onEdit',
      type: Function
      //required: true,
    },
    {
      name: 'onRemove',
      type: Function
    }
  ],

  methods: {
    onEditClick: function(item, e){
      console.log('editItem: ' + item.id.toString());
      //this.curitem = item;
      /*
       var detail = null;
       svc.get({id: item.id}, function (detail, status, request) {
       this.$set('curitem', detail)
       });
       */
      //this.setMode('modeEdit');
    },
    onRemoveClick: function(item, e){
      console.log('removeItem' + item);
      //svc.remove(item);
      //this.items.$remove(item);
      //this.setMode('modeList');
    }
  }
});

var svc = Object.create(filelist);
var Edit = Vue.extend({
  template:['<div id="add-file">',
    '<legend>添加文件</legend>',
    '<div>',
    '<label for="">书名</label>',
    '<input type="text" v-model="file.name">',
    '</div>',
    '<div >',
    '<label for="">作者</label>',
    '<input type="text" v-model="file.suffix">',
    '</div>',
    '<div>',
    '<label for="">价格</label>',
    '<input type="text" v-model="file.length">',
    '</div>',
    '<button  @click="addBook()">添加</button>',
    '</div>'].join('')
});

var Delete = Vue.extend({
  template: '<p>DELETE!</p>'
});

// 路由器需要一个根组件。
// 出于演示的目的，这里使用一个空的组件，直接使用 HTML 作为应用的模板
// because we are using the HTML as the app template.
var App = Vue.extend({});

// 创建一个路由器实例
// 创建实例时可以传入配置参数进行定制，为保持简单，这里使用默认配置
// let's keep it simple for now.
var router = new VueRouter();

// 定义路由规则
// 每条路由规则应该映射到一个组件。这里的“组件”可以是一个使用 Vue.extend
// 创建的组件构造函数，也可以是一个组件选项对象。
router.map({
  '/edit': {
    component: Edit
  }
});
// 现在我们可以启动应用了！
// 路由器会创建一个 App 实例，并且挂载到选择符 #app 匹配的元素上。
router.start(App, '#oper');

Vue.component('demo-grid', {
  template: '#grid-template',
  replace: true,
  props: {
    data: Array,
    columns: Array,
    filterKey: String
  },
  data: function () {
    var sortOrders = {};
    this.columns.forEach(function (key) {
      sortOrders[key] = 1
    });
    return {
      sortKey: '',
      sortOrders: sortOrders
    }
  },
  methods: {
    sortBy: function (key) {
      this.sortKey = key;
      this.sortOrders[key] = this.sortOrders[key] * -1
    }
  }
});

